package com.team12.hotel404.shiro;

import com.team12.hotel404.domain.Power;
import com.team12.hotel404.domain.Role;
import com.team12.hotel404.domain.User;
import com.team12.hotel404.service.AdminService;
import com.team12.hotel404.service.PowerService;
import com.team12.hotel404.service.RoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private RoleService roleService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private PowerService powerService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
       SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
       User user =(User) principalCollection.getPrimaryPrincipal();
        for (Role role:roleService.findRoleByUserId(user.getUserId())){
            authorizationInfo.addRole(role.getRoleName());
            for (Power power:powerService.findPowerByRoleId(role.getRoleId())){
                authorizationInfo.addStringPermission(power.getPowerType());
            }
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = (String)token.getPrincipal();

        User user = adminService.findByName(username);

        if (user == null){
            return null;
        }

        Object principal = user;

        Object credentials = user.getUserPassword();

        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUserName());

        String realName = getName();

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,credentialsSalt,realName);
        return info;
    }

    public static void main(String[] args) {
        String hashAlgorithmName = "MD5";
        Object credentials = "admin";
        Object salt = ByteSource.Util.bytes("admin");
        int hashIterations = 1024;
        Object result = new SimpleHash(hashAlgorithmName,credentials,salt,hashIterations);
        System.out.println(result);
    }
}
